package com.sample.hello2;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.swak.Constants;
import com.swak.OS;
import com.swak.exception.RemotingException;
import com.swak.reactivex.threads.Contexts;
import com.swak.reactivex.transport.Channel;
import com.swak.reactivex.transport.ExchangeClient;
import com.swak.reactivex.transport.ExchangeHandlerAdapter;
import com.swak.reactivex.transport.Exchangers;
import com.swak.reactivex.transport.Message;
import com.swak.reactivex.transport.TransportMode;
import com.swak.reactivex.transport.resources.LoopResources;
import com.swak.registry.URL;
import com.swak.utils.JsonMapper;
import com.swak.utils.Maps;

public class SampleClient extends ExchangeHandlerAdapter {

	private LoopResources resources = Contexts.createEventLoopResources(TransportMode.OS, 1, 2, "Sample.EventLoop-",
			false, 2, TimeUnit.SECONDS);

	ExchangeClient client;
	URL url;

	public SampleClient() throws RemotingException {
		Map<String, String> parameters = Maps.newHashMap();
		parameters.put(Constants.Bind_Host, Constants.ANYHOST);
		parameters.put(Constants.Heartbeat, String.valueOf(Constants.Default_Heartbeat));
		parameters.put(Constants.Use_Quic, "true");
		this.url = new URL("Sample", OS.ip(), 10889, parameters);
		this.client = Exchangers.connect(url, resources, this);
	}

	/**
	 * 仅仅是收到数据，对于发送的请求，不会执行此
	 */
	@Override
	public void received(Channel channel, Object message) throws RemotingException {
		System.out.println("仅仅是收到数据： " + JsonMapper.toJson(message));
	}

	public void sent(String message) throws RemotingException {
		this.client.send(Message.forMessage().setData(message));
	}

	public CompletableFuture<Object> request(String message) throws RemotingException {
		return this.client.request(Message.forRequest().addOption(Message.TwoWay).setData(message));
	}

	public static void main(String[] args) throws RemotingException, InterruptedException, ExecutionException {
		SampleClient client = new SampleClient();
		Thread.sleep(3000);
		System.out.println("推送数据:");
		client.sent("数据");
		Thread.sleep(3000);
		System.out.println("发送请求:");
		CompletableFuture<Object> future = client.request("请求的数据");
		Object result = future.get();
		System.out.println("执行结果：" + result);
	}
}
